﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace JXT.PrimaryKey.Batman.Core.Security
{
    /// <summary>
    /// AES加密帮助类
    /// </summary>
    public static class AesHelper
    {
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="buffer">数据</param>
        /// <param name="key">密钥</param>
        /// <returns>加密后数据</returns>
        public static byte[] Encode(byte[] buffer, byte[] key)
        {
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = key;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(buffer, 0, buffer.Length);
            return resultArray;
        }

        /// <summary>
        /// 使用UTF8方式加密字符串数据
        /// </summary>
        /// <param name="s">原始字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>加密后字符串</returns>
        public static string Encode(string s, string key)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(encodeKey(key));
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(s);
            return Convert.ToBase64String(Encode(toEncryptArray, keyArray));
        }

        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="buffer">加密数据</param>
        /// <param name="key">密钥</param>
        /// <returns>原始数据</returns>
        public static byte[] Decode(byte[] buffer, byte[] key)
        {
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = key;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(buffer, 0, buffer.Length);
            return resultArray;
        }

        /// <summary>
        /// 使用UTF-8方式解密字符串数据
        /// </summary>
        /// <param name="s">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>原始数据</returns>
        public static string Decode(string s, string key)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(encodeKey(key));
            byte[] toEncryptArray = Convert.FromBase64String(s);
            return Encoding.UTF8.GetString(Decode(toEncryptArray, keyArray));
        }

        private static string encodeKey(string key)
        {
            if (key.Length < 32)
            {
                return key.PadRight(32, 'x');
            }
            return key.Substring(0, 32);
        }
    }
}
